var express = require("express");
var router = express.Router();
var jwt = require("jsonwebtoken");
// 导入db ,操作数据库
const { getAll, getById, exec } = require("../db/index");

const secret = "register-rule";
/**
 * 获取所有用户
 * GET /blog
 */
router.get("/", async (req, res) => {
  // console.log(req);
  console.log(req.query);
  // 解析请求参数
  // 解构query对象,提取page,size
  // 如果没有值,就给默认值1,2
  const { page = 1, size = 2 } = req.query;
  // 获取总数
  let sql = `select count(*) as total  from gg_user`;
  const obj = await getById(sql); // { total: 10 }
  console.log(obj);

  // 根据分页公式, 计算offset偏移量
  let offset = (page - 1) * size;
  // 操作数据库
  sql = `select * from gg_user order by user_id desc  limit ${offset}, ${size}`;
  const data = await getAll(sql);

  res.send({
    code: 0,
    message: "获取用户成功",
    result: {
      total: obj.total,
      data: data,
    },
  });
});

/**
 * 新增
 */

router.post("/", async (req, res) => {
  const { user_name, user_password, user_type } = req.body;
  // const { page = 1, size = 2 } = req.query;
  let sql = `insert into gg_user (user_name,user_password,user_type)  values  ('${user_name}', '${user_password}','${user_type}')`;
  const data = await exec(sql);
  console.log(data);
  res.send({
    code: 0,
    message: "新增用户成功",
    result: {
      user_id: data.insertId,
      user_name,
      user_password,
      user_type,
    },
  });
});

// 根据id获取
router.get("/:id", async (req, res) => {
  const { id } = req.params;
  let sql = `select * from gg_user where user_id = ${id}`;
  const data = await getById(sql);
  res.send({
    code: 0,
    message: "获取用户成功",
    result: {
      data,
    },
  });
});

// 根据用户查密码
router.post("/username", async (req, res) => {
  const { user_name } = req.body;
  let sql = `select user_id,user_name,user_password from gg_user where user_name = '${user_name}'`;
  const data = await getById(sql);
  if (data) {
    res.send({
      code: 0,
      message: "获取用户成功",
      result: {
        data,
      },
    });
  } else {
    res.send({
      code: 1001,
      message: "没有该用户",
    });
  }
});

// 修改账户密码请求
router.put("/:id", async (req, res) => {
  const { id } = req.params;
  const { user_name, user_password } = req.body;
  let sql = `update gg_user set user_name='${user_name}',
                                 user_password='${user_password}'
                                  
              where user_id=${id} `;
  const data = await exec(sql);
  res.send({
    code: 0,
    message: "修改用户成功",
    result: {
      user_id: id,
      user_name,
      user_password,
    },
  });
});

// 删除
router.delete("/:id", async (req, res) => {
  const { id } = req.params;
  let sql = `delete from gg_user where user_id=${id}`;
  await exec(sql);
  res.send({
    code: 0,
    message: "删除成功",
    result: "",
  });
});

// 登录
router.post("/login", async (req, res) => {
  const { user_name, user_password } = req.body;
  if (!user_name && !user_password) {
    return res.send({
      code: 100104,
      message: "参数格式不对",
      result: "用户密码不能为空",
    });
  }
  let sql = `select * from gg_user`;
  const resData = await getAll(sql);
  console.log(resData);
  let user = resData.map((item) => item.user_name);
  // let ps = resData.map((item) => item.user_password);
  // let id = resData.map((item) => item.user_id);
  if (!user.includes(user_name)) {
    return res.send("该用户不存在");
  }
  if (user.includes(user_name)) {
    let sql2 = `select * from gg_user where user_name='${user_name}'`;
    const dataByName = await getAll(sql2);

    let sql1 = `select user_password from gg_user where user_name='${user_name}'`;
    const psw = await getAll(sql1);
    console.log(psw);
    if (user_password == psw[0].user_password) {
      let token = jwt.sign({ user_name }, secret, { expiresIn: "24h" });
      return res.send({
        code: 0,
        message: "登录成功",
        result: {
          data: dataByName,
          token,
        },
      });
    } else {
      return res.send({
        code: 1004,
        message: "密码错误",
      });
    }
  }
});

module.exports = router;
